/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 16.09.2009, 20:49:21
 */
package de.jugms.sd.main;

/**
 * 
 * @author hansolo
 */
public class MainFrame extends javax.swing.JFrame implements java.awt.event.ActionListener,
        java.awt.event.FocusListener, java.awt.event.MouseListener,
        java.awt.event.MouseMotionListener, java.awt.event.WindowListener,
        java.awt.event.KeyListener, javax.swing.event.DocumentListener,
        de.jugms.sd.components.textfields.ValidationEventListener {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    javax.swing.JDialog optionDialog;

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        this.addMouseListener(this);
        this.addMouseMotionListener(this);
        this.addWindowListener(this);

        // Prepare glass pane
        this.setGlassPane(glass);
        glass.setVisible(true);

        // Add action listener
        inputPanel.cancelButton.addActionListener(this);
        inputPanel.submitButton.addActionListener(this);

        // Add focus listener
        inputPanel.textPaneComment.addFocusListener(this);

        // Add key listener
        inputPanel.textPaneComment.addKeyListener(this);

        // Customized ScrollBar to scrollPane
        de.jugms.sd.components.misc.SDScrollBar bar = new de.jugms.sd.components.misc.SDScrollBar();
        inputPanel.scrollPaneComment.setVerticalScrollBar(bar);

        // Add document listener
        inputPanel.textPaneComment.getDocument().addDocumentListener(this);
        inputPanel.textFieldPhone.getDocument().addDocumentListener(this);

        // Add validation listener
        inputPanel.textFieldFirstName.addValidationEventListener(this);
        inputPanel.textFieldLastName.addValidationEventListener(this);
        inputPanel.textFieldMail.addValidationEventListener(this);
        inputPanel.textFieldSubject.addValidationEventListener(this);

        // Option dialog
        optionDialog = new de.jugms.sd.main.OptionDialog(this, rootPaneCheckingEnabled);
        optionDialog.setVisible(false);

        // Add marks to components
        glass.addMarker(inputPanel.textFieldFirstName);
        glass.addMarker(inputPanel.textFieldLastName);
        glass.addMarker(inputPanel.textFieldMail);
        glass.addMarker(inputPanel.textFieldSubject);

        // Add mouse listener
        footer.addMouseListener(this);

        // Add mouse motion listener
        footer.addMouseMotionListener(this);

        // Validate form
        checkForm();

        // Place frame in center of screen
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated
    // Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        new javax.swing.ButtonGroup();
        backgroundPanel = new de.jugms.sd.components.panels.SDLinearGradientPanel();
        titleBarPanel = new de.jugms.sd.components.panels.SDTitleBar();
        bubblePanel = new de.jugms.sd.components.panels.SDBubblePanel();
        footer = new de.jugms.sd.components.panels.SDFooter();
        inputPanel = new de.jugms.sd.components.panels.SDInputPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(354, 462));
        setUndecorated(true);

        backgroundPanel.setName("backgroundPanel"); // NOI18N

        titleBarPanel.setName("titleBarPanel"); // NOI18N
        titleBarPanel.setTitle("Swing Demo");

        bubblePanel.setName("bubblePanel"); // NOI18N

        javax.swing.GroupLayout bubblePanelLayout = new javax.swing.GroupLayout(bubblePanel);
        bubblePanel.setLayout(bubblePanelLayout);
        bubblePanelLayout.setHorizontalGroup(bubblePanelLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 342, Short.MAX_VALUE));
        bubblePanelLayout.setVerticalGroup(bubblePanelLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 60, Short.MAX_VALUE));

        footer.setName("footer"); // NOI18N

        javax.swing.GroupLayout footerLayout = new javax.swing.GroupLayout(footer);
        footer.setLayout(footerLayout);
        footerLayout.setHorizontalGroup(footerLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 354, Short.MAX_VALUE));
        footerLayout.setVerticalGroup(footerLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 24, Short.MAX_VALUE));

        inputPanel.setBorder(null);
        inputPanel.setName("inputPanel"); // NOI18N

        javax.swing.GroupLayout backgroundPanelLayout = new javax.swing.GroupLayout(backgroundPanel);
        backgroundPanel.setLayout(backgroundPanelLayout);
        backgroundPanelLayout.setHorizontalGroup(backgroundPanelLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(titleBarPanel,
                javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                backgroundPanelLayout.createSequentialGroup().addContainerGap().addComponent(
                        inputPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                        .addGap(5, 5, 5)).addGroup(
                backgroundPanelLayout.createSequentialGroup().addContainerGap().addComponent(
                        bubblePanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap())
                .addComponent(footer, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE));
        backgroundPanelLayout.setVerticalGroup(backgroundPanelLayout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                backgroundPanelLayout.createSequentialGroup().addComponent(titleBarPanel,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(
                        bubblePanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(
                        javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(
                        inputPanel, javax.swing.GroupLayout.PREFERRED_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(footer,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        javax.swing.GroupLayout.DEFAULT_SIZE,
                        javax.swing.GroupLayout.PREFERRED_SIZE)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(backgroundPanel,
                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(backgroundPanel,
                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                Short.MAX_VALUE));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void checkForm() {
        // Enable radioButtonPhone only if textFieldPhone has valid input
        inputPanel.radioButtonPhone.setEnabled(inputPanel.textFieldPhone.validateData());
        inputPanel.radioButtonMail.setSelected(!inputPanel.radioButtonPhone.isEnabled());

        // TextPane Comment
        if (inputPanel.textPaneComment.getText().isEmpty()
                || inputPanel.textPaneComment.getText().equals("comment...")) {
            glass.addMarker(inputPanel.scrollPaneComment);
            inputPanel.textPaneComment.setForeground(INACTIVE_FOREGROUND_COLOR);
        } else {
            glass.removeMarker(inputPanel.scrollPaneComment);
            inputPanel.textPaneComment.setForeground(ACTIVE_FOREGROUND_COLOR);
        }

        // If everything is OK enable the Submit Button
        if (glass.isEverythingOK()) {
            bubblePanel.setFormComplete(true);
            inputPanel.submitButton.setEnabled(true);
            glass.addOkMarker(inputPanel.submitButton);
        } else {
            bubblePanel.setFormComplete(false);
            inputPanel.submitButton.setEnabled(false);
            glass.removeOkMarker(inputPanel.submitButton);
        }
    }

    public void resetForm() {
        javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {
            @Override
            public void run() {
                inputPanel.textFieldFirstName.reset();
                inputPanel.textFieldLastName.reset();
                inputPanel.textFieldMail.reset();
                inputPanel.textFieldPhone.reset();
                inputPanel.radioButtonMail.setSelected(true);
                inputPanel.textFieldSubject.reset();
                inputPanel.textPaneComment.setText("comment...");
                inputPanel.textPaneComment
                        .setForeground(new java.awt.Color(1.0f, 1.0f, 1.0f, 0.6f));
                inputPanel.progressBar.setInfinite(false);
                inputPanel.submitButton.setEnabled(false);
                bubblePanel.setFormComplete(false);
                glass.resetGlassPane();
                checkForm();
            }
        });
    }

    public void setTranslucent(boolean transparent) {
        if (transparent) {
            // Try to set frame transparency via reflection
            try {
                Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
                java.lang.reflect.Method mSetWindowOpacity = awtUtilitiesClass.getMethod(
                        "setWindowOpacity", java.awt.Window.class, float.class);
                mSetWindowOpacity.invoke(null, this, Float.valueOf(0.9f));
            } catch (NoSuchMethodException exception) {
                exception.printStackTrace();
            } catch (SecurityException exception) {
                exception.printStackTrace();
            } catch (ClassNotFoundException exception) {
                exception.printStackTrace();
            } catch (IllegalAccessException exception) {
                exception.printStackTrace();
            } catch (IllegalArgumentException exception) {
                exception.printStackTrace();
            } catch (java.lang.reflect.InvocationTargetException exception) {
                exception.printStackTrace();
            }
        } else {
            // Try to set frame transparency via reflection
            try {
                Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
                java.lang.reflect.Method mSetWindowOpacity = awtUtilitiesClass.getMethod(
                        "setWindowOpacity", java.awt.Window.class, float.class);
                mSetWindowOpacity.invoke(null, this, Float.valueOf(1.0f));
            } catch (NoSuchMethodException exception) {
                exception.printStackTrace();
            } catch (SecurityException exception) {
                exception.printStackTrace();
            } catch (ClassNotFoundException exception) {
                exception.printStackTrace();
            } catch (IllegalAccessException exception) {
                exception.printStackTrace();
            } catch (IllegalArgumentException exception) {
                exception.printStackTrace();
            } catch (java.lang.reflect.InvocationTargetException exception) {
                exception.printStackTrace();
            }

        }
    }

    @Override
    public void paint(java.awt.Graphics g) {
        super.paint(g);
        if (getRootPane().getJMenuBar() != null) {
            getRootPane().getJMenuBar().setLocation(0,
                    titleBarPanel.getY() + titleBarPanel.getHeight());
        }
    }

    // ActionListener methods
    @Override
    public void actionPerformed(java.awt.event.ActionEvent event) {
        if (event.getSource().equals(inputPanel.cancelButton)) {
            exitApplication();
        }

        if (event.getSource().equals(inputPanel.submitButton)) {
            Thread submission = new Thread(new java.lang.Runnable() {
                @Override
                public void run() {
                    inputPanel.progressBar.setInfinite(true);
                    try {
                        Thread.sleep(10000);
                    } catch (java.lang.InterruptedException exception) {

                    }
                    javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {

                        @Override
                        public void run() {
                            inputPanel.progressBar.setInfinite(false);
                            resetForm();
                        }
                    });
                }
            });
            submission.start();
        }
    }

    // FocusListener methods
    @Override
    public void focusGained(java.awt.event.FocusEvent event) {
        // TextPane Comment
        if (event.getSource() == inputPanel.textPaneComment) {
            if (inputPanel.textPaneComment.getText().equals("comment...")) {
                javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {
                    @Override
                    public void run() {
                        // Handler logic
                        inputPanel.textPaneComment.setForeground(ACTIVE_FOREGROUND_COLOR);
                        inputPanel.textPaneComment.setText("");
                    }
                });
            }
            ((de.jugms.sd.components.panels.SDScrollPaneViewport) inputPanel.scrollPaneComment
                    .getViewport()).setFocused(true);
        }

        checkForm();
    }

    @Override
    public void focusLost(java.awt.event.FocusEvent event) {
        // TextPane Comment
        if (event.getSource() == inputPanel.textPaneComment) {
            if (inputPanel.textPaneComment.getText().isEmpty()) {
                javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {
                    @Override
                    public void run() {
                        // Handler logic
                        inputPanel.textPaneComment.setForeground(INACTIVE_FOREGROUND_COLOR);
                        inputPanel.textPaneComment.setText("comment...");
                    }
                });
            }
            ((de.jugms.sd.components.panels.SDScrollPaneViewport) inputPanel.scrollPaneComment
                    .getViewport()).setFocused(false);
        }
    }

    // MouseListener methods
    @Override
    public void mouseClicked(java.awt.event.MouseEvent event) {
        if (event.getSource() instanceof de.jugms.sd.components.panels.SDFooter) {
            if (footer.getOptionHotSpot().contains(event.getPoint()) && !optionDialog.isVisible()) {
                optionDialog.setLocation(getLocation().x + getPreferredSize().width + 20,
                        getLocation().y);
                optionDialog.setVisible(true);
            }
        }
    }

    @Override
    public void mousePressed(java.awt.event.MouseEvent event) {
        if (!event.isMetaDown()) {
            point.x = event.getX();
            point.y = event.getY();
        }
    }

    @Override
    public void mouseReleased(java.awt.event.MouseEvent event) {
    }

    @Override
    public void mouseEntered(java.awt.event.MouseEvent event) {
    }

    @Override
    public void mouseExited(java.awt.event.MouseEvent event) {
    }

    // MouseMotionListener methods
    @Override
    public void mouseDragged(java.awt.event.MouseEvent event) {
        if (!event.isMetaDown()) {
            java.awt.Point p = getLocation();

            if (getCursor().getType() != java.awt.Cursor.DEFAULT_CURSOR) {
                setSize(event.getLocationOnScreen().x - p.x, event.getLocationOnScreen().y - p.y);
                validate();
            } else {
                setLocation(p.x + event.getX() - point.x, p.y + event.getY());
            }
        }
    }

    @Override
    public void mouseMoved(java.awt.event.MouseEvent event) {
        // Resizer
        if (event.getSource() instanceof de.jugms.sd.components.panels.SDFooter) {
            if (footer.getResizerHotSpot().contains(event.getPoint())) {
                setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.SE_RESIZE_CURSOR));
            } else {
                setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
            }
        } else {
            setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
    }

    // WindowListener methods
    @Override
    public void windowOpened(java.awt.event.WindowEvent event) {
    }

    @Override
    public void windowClosing(java.awt.event.WindowEvent event) {
    }

    @Override
    public void windowClosed(java.awt.event.WindowEvent event) {
    }

    @Override
    public void windowIconified(java.awt.event.WindowEvent event) {
    }

    @Override
    public void windowDeiconified(java.awt.event.WindowEvent event) {
    }

    @Override
    public void windowActivated(java.awt.event.WindowEvent event) {
        javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {
            @Override
            public void run() {
                // Handler logic
                glass.setDisabled(false);
            }
        });
    }

    @Override
    public void windowDeactivated(java.awt.event.WindowEvent event) {
        javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable() {
            @Override
            public void run() {
                // Handler logic
                if (!optionDialog.isVisible()) {
                    glass.setDisabled(true);
                }
            }
        });
    }

    // KeyListener methods
    @Override
    public void keyTyped(java.awt.event.KeyEvent event) {

    }

    @Override
    public void keyPressed(java.awt.event.KeyEvent event) {
        if (event.getSource().equals(inputPanel.textPaneComment)) {
            if (event.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {
                if (event.getModifiers() > 0) {
                    transferFocusBackward();
                } else {
                    transferFocus();
                }
                event.consume();
            }
        }
    }

    @Override
    public void keyReleased(java.awt.event.KeyEvent event) {

    }

    // DocumentListener methods
    @Override
    public void insertUpdate(javax.swing.event.DocumentEvent event) {
        checkForm();
    }

    @Override
    public void removeUpdate(javax.swing.event.DocumentEvent event) {
        checkForm();
    }

    @Override
    public void changedUpdate(javax.swing.event.DocumentEvent event) {
        checkForm();
    }

    // ValidationEventListener methods
    @Override
    public void validationEventPerformed(de.jugms.sd.components.textfields.ValidationEvent event) {
        if (event.isValid()) {
            glass.removeMarker((javax.swing.JComponent) event.getSource());
        } else {
            glass.addMarker((javax.swing.JComponent) event.getSource());
        }

        // If everything is OK enable the Submit Button
        if (glass.isEverythingOK()) {
            bubblePanel.setFormComplete(true);
            inputPanel.submitButton.setEnabled(true);
            glass.addOkMarker(inputPanel.submitButton);
        } else {
            bubblePanel.setFormComplete(false);
            inputPanel.submitButton.setEnabled(false);
            glass.removeOkMarker(inputPanel.submitButton);
        }
    }

    private void exitApplication() {
        javax.swing.PopupFactory.setSharedInstance(new javax.swing.PopupFactory());
        System.exit(0);
    }

    @Override
    public String toString() {
        return "MainFrame";
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                de.jugms.sd.tools.SDGlobalAnimationTimer.INSTANCE.start();
                de.jugms.sd.tools.SDGlobals.INSTANCE
                        .setActiveGradient(de.jugms.sd.tools.SDTwoColorGradients.BLUE);
                de.jugms.sd.tools.SDGlobals.INSTANCE
                        .setActiveTranspaGradient(de.jugms.sd.tools.SDTwoColorGradients.BLUE_TRANSPA);
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private de.jugms.sd.components.panels.SDLinearGradientPanel backgroundPanel;
    public de.jugms.sd.components.panels.SDBubblePanel bubblePanel;
    private de.jugms.sd.components.panels.SDFooter footer;
    public de.jugms.sd.components.panels.SDInputPanel inputPanel;
    public de.jugms.sd.components.panels.SDTitleBar titleBarPanel;
    // End of variables declaration//GEN-END:variables
    public de.jugms.sd.components.panels.SDGlassPane glass = new de.jugms.sd.components.panels.SDGlassPane(
            de.jugms.sd.components.panels.SDGlassPane.MARKER_TYPE.RED_TRIANGLE);
    private final java.awt.Color INACTIVE_FOREGROUND_COLOR = new java.awt.Color(1.0f, 1.0f, 1.0f,
            0.6f);
    private final java.awt.Color ACTIVE_FOREGROUND_COLOR = new java.awt.Color(1.0f, 1.0f, 1.0f,
            0.9f);
    private static java.awt.Point point = new java.awt.Point(0, 0);
}
